package demo.shiro.action;

import demo.shiro.service.UserService;
import org.smart4j.framework.ioc.annotation.Inject;
import org.smart4j.framework.mvc.DataContext;
import org.smart4j.framework.mvc.annotation.Action;
import org.smart4j.framework.mvc.annotation.Request;
import org.smart4j.framework.mvc.bean.Params;
import org.smart4j.framework.mvc.bean.View;
import org.smart4j.security.exception.LoginException;

@Action
public class LoginAction {

    @Inject
    private UserService userService;

    @Request.Get("/login")
    public View index() {
        // 转发到登录页面
        return new View("login.jsp");
    }

    @Request.Post("/login")
    public View submit(Params params) {
        // 获取表单数据
        String username = params.getString("username");
        String password = params.getString("password");
        boolean isRememberMe = params.getString("rememberMe") != null;

        // 调用登录服务
        try {
            userService.login(username, password, isRememberMe);
        } catch (LoginException e) {
            DataContext.Request.put("exception", e.getName());
            return index();
        }

        // 重定向到空间页面
        return new View("/space");
    }
}
